package com.onesports.rabbitmq.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: HUANG GY.
 * @Date: 2020/6/19 15:01
 * @Description: 对应的手动确认消息监听类 （手动确认模式需要实现 ChannelAwareMessageListener）
 */
@Component
public class MyAckReceiver implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //因为传递消息的时候用的map传递,所以将Map从Message内取出需要做些处理
            String msg = message.toString();
            //可以点进Message里面看源码,单引号直接的数据就是我们的map消息数据
            String[] msgArray = msg.split("'");
//            Map<String, String> msgMap = mapStringToMap(msgArray[1].trim());
//            String messageId=msgMap.get("messageId");
//            String messageData=msgMap.get("messageData");
//            String createTime=msgMap.get("createTime");
//            System.out.println("  MyAckReceiver  messageId:"+messageId+"  messageData:"+messageData+"  createTime:"+createTime);
            System.out.println("收到的消息："+msgArray);
            if (deliveryTag <= 2 ){
                throw new IllegalAccessException("我 是 异常 ") ;
            }
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            //为true会重新放回队列
            channel.basicReject(deliveryTag, true);
//            channel.basicReject(deliveryTag, false);
            e.printStackTrace();
        }
    }

    /**
     *  {key=value,key=value,key=value} 格式转换成map
     * @param str
     * @return
     */
    private Map<String, String> mapStringToMap(String str) {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        Map<String, String> map = new HashMap<String, String>();
        for (String string : strs) {
            String key = string.split("=")[0].trim();
            String value = string.split("=")[1];
            map.put(key, value);
        }
        return map;
    }
}
